<?php


namespace app\api\service;


use app\api\model\Dish;
use app\lib\enum\OrdersStatusEnum;
use think\Db;
use think\Exception;
use think\Log;
use wechatpay\handler\WxPayNotify;

class WxNotify extends WxPayNotify
{
    // 覆盖WxPayNotify
    public function NotifyProcess($data, &$msg)
    {
        if ($data['result_code'] == 'SUCCESS') {
            $ordersCode = $data['out_trade_no'];
            // 使用事务防止多次减库存
            Db::startTrans();
            try {
                $orders = \app\api\model\Orders::where('orders_code', '=', $ordersCode)
                    ->lock(true)
                    ->find();
                // 更新订单状态
                if ($orders->orders_state == OrdersStatusEnum::unPaid) {
                    $service = new Orders();
                    $status = $service->checkDishNum($orders->id);
                    if ($status['pass']) {
                        $this->updateOrdersState($orders->id, true);
                        $this->reduceDishNum($status);
                    } else {
                        $this->updateOrdersState($orders->id, false);
                    }
                }
                Db::commit();
                return true;
            } catch (Exception $e) {
                Db::rollback();
                Log::error($e);
                return false;
            }
        } else {
            // 已经知晓支付失败，返回true微信不会继续通知
            return true;
        }
    }

    // 更新订单状态
    public function updateOrdersState($ordersID, $success)
    {
        /*$state = OrdersStatusEnum::unPaid;
        $order = \app\api\model\Orders::where('id', '=', $ordersID)->find();
        $time = $order->create_time + 60;
        if ($state && time() > $time) {
            \app\api\model\Orders::where('id', '=', $ordersID)->delete();
        }*/
        $status = $success?OrdersStatusEnum::paid:OrdersStatusEnum::paid_no_num;
        \app\api\model\Orders::where('id', '=', $ordersID)->update(['orders_state' => $status]);
    }

    // 更新库存
    public function reduceDishNum($status)
    {
        Db::startTrans();
        try {
            foreach ($status['dStatusArray'] as $singleDStatus) {
                Dish::where('id', '=', $singleDStatus['id'])
                    ->setDec('dish_num', $singleDStatus['order_count']);
                Dish::where('id', '=', $singleDStatus['id'])
                    ->setInc('dish_count', $singleDStatus['order_count']);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
        }

    }
}